package com.scratch.common.utils;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

@Slf4j
public class QrCodeUtil {

    /**
     * @param orderCode
     * @param orderTime
     * @return
     */
    public static String orderQrCodeEncrypt(String orderCode, Long orderTime) {

        try {
            String key = "999" + orderTime;
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),
                    key.getBytes()).getEncoded();
            SymmetricCrypto aes = SecureUtil.aes(byteKey);
            // 加密
            return aes.encryptBase64(orderCode);
        } catch (Exception e) {
            log.error(" 加密异常:{}", e.getMessage());
        }
        return null;
    }

    public static String orderQrCodeDecrypt(String data, Long orderTime) {
        try {
            String key = "999" + orderTime;
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),
                    key.getBytes()).getEncoded();
            SymmetricCrypto aes = SecureUtil.aes(byteKey);
            //解密
            return aes.decryptStr(data);
        } catch (Exception e) {
            log.error(" 解密异常:{}", e.getMessage());
        }
        return null;
    }


    public static String getInet4Address() {
        Enumeration nis;
        String ip = null;
        try {
            nis = NetworkInterface.getNetworkInterfaces();
            for (; nis.hasMoreElements(); ) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration ias = ni.getInetAddresses();
                for (; ias.hasMoreElements(); ) {
                    InetAddress ia = (InetAddress) ias.nextElement();
                    if (ia instanceof Inet4Address && !ia.getHostAddress().equals("127.0.0.1")) {
                        ip = ia.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

        return ip;
    }

    public static String getQrCodeUrl(Integer money, String orderNo) {
        return "http://" + getInet4Address() + ":8080" + "/wxpay/index.html#/pages/payAuth?money=" + money + "&orderNo=" + orderNo;
    }

    public static void main(String args[]) {
        System.out.println(getQrCodeUrl(1, "2"));
    }
}
